<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\StoreBlogPost;

use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;

use App\Models\EmailAlert;

use Validator;

/**
 *
 */
class AlertController extends Controller
{
    public function index()
    {
        return view('alert.index',[]);
    }

    public function save(Request $request)
    {

        $captchaInput = $request->get('captcha');
        $captcha = session()->get('captcha');


        $validator = Validator::make($request->all(), [
            'email' => 'required|email|unique:email_alerts',
            'captcha' => 'required'
        ], [
            'email.required' => 'email must be required',
            'email.unique' => 'email has been alerted',
            'captcha.required' => 'captcha must be required'
        ]);

        $sameCaptcha = $captchaInput == $captcha;
        $validator->after(function($validator) use ($sameCaptcha) {
            if (!$sameCaptcha) {
                $validator->errors()->add('captcha.same', 'captcha is incorrect');
            }
        });


        if ($validator->fails()) {
            // print_r($validator->errors());exit;
            return redirect(route('alert.index'))
                ->withErrors($validator)
                ->withInput();
        }

        $params = $request->all();
        $default = function($val) use ($params) {
            return isset($params[$val]) ? $params[$val] : 0;
        };
        EmailAlert::create([
            'email' => $params['email'],
            'table_of_content' => $default('table_of_content'),
            'asap_published' => $default('asap_published'),
            'search_keywords' => $default('search_keywords'),
            'keywords' => isset($params['keywords']) ? $params['keywords'] : '',
            'high_light' => $default('high_light')
        ]);

        
        return redirect(route('alert.index'))->with('status', $params['email'] . ' 保存成功');
    }

    public function captcha($tmp)
    {
        $phraseBuilder = new PhraseBuilder(4, '0123456789');

        $builder = new CaptchaBuilder(null, $phraseBuilder);
        $builder->build();
        header('Content-type: image/jpeg');
        session()->put('captcha', $builder->getPhrase());
        $builder->output();
    }
}